<script>
import config from '@/config/app.config.js';

/* 导航菜单 */
export default {
  props: {
    height: Number
  },
  render(h) {
    const styles = {
      textColor: '#303133',
      iconColor: '#909399'
    };
    let children = this.menuTreeNodes.map(node => buildSubmenu(node, 1));

    return h(
      'el-aside',
      {
        attrs: {
          id: 'nav-menu-aside'
        },
        style: {
          visibility: this.visible ? 'visible' : 'hidden',
          position: 'relative',
          width: 'unset',
          height: this.height + 'px'
        }
      }, [
        h(
          'el-menu',
          {
            ref: 'menu',
            props: {
              collapse: this.collapse,
              uniqueOpened: true,
              ...styles
            },
            class: 'main-menu',
            on: {
              select: this.onSelect
            }
          },
          children
        ),
        h('div',
          {
            class: 'menu-fold-button',
            style: {color: styles.iconColor},
            on: {
              click: this.onMenuFoldButtonClick
            }
          },
          [
            h('i', {
              class: `el-icon-s-${this.collapsed ? 'unfold' : 'fold'}`,
            })
          ]
        ),
      ]);

    function buildSubmenu(node, level) {
      if (node.children && node.children.length) {
        return h(
          'el-submenu',
          {
            props: {
              index: node.id + ''
            }
          }, [
            h('template', {slot: 'title'}, [
              level == 1 && h('i',
                {
                  class: `el-icon-${node.iconCls || 'menu'}`,
                  style: {color: styles.iconColor}
                }),
              h('span', node.text)
            ])
          ].concat(node.children.map(node => buildSubmenu(node, level + 1))));
      } else {
        return h(
          'el-menu-item',
          {
            props: {index: node.id + ''}
          },
          [h('template', {slot: 'title'}, [
            level == 1 && h('i',
              {
                class: `el-icon-${node.iconCls || 'menu'}`,
                style: {color: styles.iconColor}
              }),
            h('span', node.text)
          ])]
        );
      }
    }
  },
  data() {
    return {
      visible: false,
      collapse: true,
      collapsed: true,
      menuTreeNodes: [],
    }
  },
  computed: {
    menuIndexMap() {
      let map = new Map();
      createMenuMap(this.menuTreeNodes);
      function createMenuMap(nodes) {
        nodes.forEach(node => {
          if (!(node.children && node.children.length))
            map.set(node.id+'', node);
          if (node.children)
          createMenuMap(node.children);
        });
      }
      return map;
    },
    collapsedWidth() { return 64; },
    expandedWidth() { return 202; }
  },
  watch: {
    collapse(value) {
      this.timer && clearInterval(this.timer);

      let menuEl = this.$el.children[0];
      
      if (menuEl == null) {
        clearInterval(this.timer);
        return;
      }

      let { collapsedWidth, expandedWidth } = this;
      this.$emit('after-collapse-change', value);
      this.timer = setInterval(() => {
        if (value) {
          if (menuEl.offsetWidth <= collapsedWidth) {
            clearInterval(this.timer);
            this.timer = null;
            this.collapsed = true;
            this.$emit('collapsed');
            this.$emit('collapse-change', true);
          }
        } else {
          if (menuEl.offsetWidth >= expandedWidth) {
            clearInterval(this.timer);
            this.timer = null;
            this.collapsed = false;
            this.$emit('expanded');
            this.$emit('collapse-change', false);
          }
        }
      }, 16);
    }
  },
  methods: {
    loadMenus(nodes) {
      const filterMenuNodes = (nodes, parent) => {
        let menuNodes = [];
        nodes.forEach(node => {
          if (node.attributes && node.attributes.isMenu) {
            node = {...node};
            menuNodes.push(node);
            if (node.children) {
              node.children = filterMenuNodes(node.children, node);
            }
          }
        });
        return menuNodes;
      };
      const menuIconMap = {
        'home': 'house',
        'smart_info_center': 'user',
        'pension_service_center': 'goods',
        'datastat': 'data-board',
        'operation_monitor_center': 'monitor',
        'intelligent_sunshine_management': 'sunny',
        'health': 'star-off',
        'system': 'setting',
        'help': 'help'
      };
      this.menuTreeNodes = filterMenuNodes(nodes).map((node) => {
        node.iconCls = menuIconMap[node.attributes.code];
        return node;
      });
    },
    perform() {
      this.visible = true;
      this.$nextTick(() => {
        let initCollapse = !config.get('navMenuExpanded');
        this.setCollapse(initCollapse);
        this.collapsed = initCollapse;
      });
    },
    switchCollapse() {
      this.setCollapse(!this.collapse);
    },
    setCollapse(collapseWill) {
      if (collapseWill) {
        if (this.collapse) {
          // 已折叠时立即发送事件
          if (this.collapsed) {
            this.$emit('collapsed');
          }
        } else {
          this.collapse = true;
        }
      } else {
        if (!this.collapse) {
          // 已展开时立即发送事件
          if (!this.collapsed) {
            this.$emit('expanded');
          }
        } else {
          this.collapse = false;
        }
      }
    },
    onMenuFoldButtonClick() {
      this.switchCollapse();
    },
    onSelect(index) {
      const item = this.menuIndexMap.get((index || '').toString());
      if (item) {
        app.oldApiOpenPageBridge(item);
      }
    },
    open(index) {
      this.$refs.menu.open(index);
    }
  }
};
</script>

<style scoped>
.el-aside > .el-menu {
  border-right: none;
}
.el-aside > .menu-fold {
  transition: color .2s ease;
  color: #909399;
}
.el-aside > .menu-fold:hover {
  color: #000;
}
</style>
<style lang="scss" scoped>
.el-aside {
  overflow: hidden;
  overflow-x: hidden;
  box-shadow: 2px 0 6px rgba(0,21,41,.04);
  background: #fff;
}
.el-aside:hover {
  overflow-y: auto;
}
.el-aside::-webkit-scrollbar {
  display: none;
}

.el-menu-item.is-active {
  color: #303133;
}

.main-menu {
  height: calc(100% - 40px);
  overflow-x: hidden;
  overflow-y: auto;
}
.main-menu::-webkit-scrollbar {
  width: 4px;
}
.main-menu::-webkit-scrollbar-thumb {
    background-color: #DCDFE6;
}
.main-menu:not(.el-menu--collapse) {
  width: 202px;
}

.menu-fold-button {
  width: 100%;
  height: 38px;
  border-top: 1px solid #F2F6FC;
  border-bottom: 1px solid transparent;
  text-align: left;
  font-size: 20px;
  cursor: pointer;
  background: #fff;
  transition: 0.1s color ease;
}
.menu-fold-button:hover {
  color: #303133 !important;
}
.menu-fold-button > i {
  margin-left: 21px;
  line-height: 38px;
  color: inherit;
}
</style>
